package cn.tedu.myweb.service.impl;

import cn.tedu.myweb.exception.ServiceException;
import cn.tedu.myweb.mapper.UserPermissionMapper;
import cn.tedu.myweb.mapper.UserMapper;
import cn.tedu.myweb.model.User;
import cn.tedu.myweb.model.UserPermission;
import cn.tedu.myweb.service.IUserService;
import cn.tedu.myweb.vo.RegisterVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    UserPermissionMapper permissionMapper;

    public String errorMessage="";

    @Override
    public void register(RegisterVo registerVo) {

        User user = userMapper.findUserByUsername(registerVo.getUsername());
        if(user!=null){
            errorMessage="用户名已经存在！";
            throw new ServiceException(errorMessage);
        }
        user = userMapper.findUserByPhone(registerVo.getPhone());
        if(user!=null){
            errorMessage="手机号已经被注册！";
            throw new ServiceException(errorMessage);
        }
        user = userMapper.findUserByEmail(registerVo.getEmail());
        if(user!=null){
            errorMessage="邮箱已经被注册！";
            throw new ServiceException(errorMessage);
        }

        PasswordEncoder encoder = new BCryptPasswordEncoder();
        String pwd = "{bcrypt}"+encoder.encode(registerVo.getPassword());

        User u = new User()
                .setUsername(registerVo.getUsername())
                .setPhone(registerVo.getPhone())
                .setEmail(registerVo.getEmail())
                .setPassword(pwd)
                .setRegTime(LocalDateTime.now());
        int num = userMapper.insert(u);
        UserPermission up1 = new UserPermission()
                .setUserId(u.getId())
                        .setPermissionId(1);
        UserPermission up2 = new UserPermission()
                .setUserId(u.getId())
                .setPermissionId(2);
        permissionMapper.insert(up1);
        permissionMapper.insert(up2);
        if(num!=1){
            errorMessage="数据库忙！";
            throw new ServiceException(errorMessage);
        }
    }

    @Override
    public User addFriendsByName(String name) {
        User user = userMapper.findUserByUsername(name);
        if(user==null){
            return null;
        }
        return user;
    }

    @Override
    public User addFriendsByPhone(String phone) {
        User user = userMapper.findUserByPhone(phone);
        if(user==null){
            return null;
        }
        return user;
    }
}
